package edu.pw.p2pclient.networking;

import java.net.InetAddress;
import java.net.UnknownHostException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class MessageSender {

	private static String TAG = "MessageSender";

	private Context mAppContext;
	private volatile InetAddress mBroadcastAddress;
	private InetAddress mMyDeviceAddress;

	public MessageSender(Context appContext) {

		mAppContext = appContext;
		mBroadcastAddress = null;
		mMyDeviceAddress = null;
	}

	public synchronized void resetAddresses() {

		mBroadcastAddress = null;
		mMyDeviceAddress = null;
	}

	public synchronized InetAddress getBroadcastAddress() {

		if (mBroadcastAddress == null)
			setAddresses();
		return mBroadcastAddress;
	}

	public synchronized InetAddress getMyDeviceAddress() {

		if (mMyDeviceAddress == null)
			setAddresses();
		return mMyDeviceAddress;
	}

	@SuppressLint("DefaultLocale")
	private synchronized void setAddresses() {

		Log.i(TAG, "setAddresses()");
		WifiManager manager = (WifiManager) mAppContext
				.getSystemService(Context.WIFI_SERVICE);

		int ip = manager.getConnectionInfo().getIpAddress();

		try {
			mMyDeviceAddress = InetAddress.getByName(String.format(
					"%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff),
					(ip >> 16 & 0xff), (ip >> 24 & 0xff)));
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			mMyDeviceAddress = null;
		}

		DhcpInfo dhcp = manager.getDhcpInfo();
		if (dhcp == null)
			return;

		int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++)
			quads[k] = (byte) (broadcast >> k * 8);
		try {
			mBroadcastAddress = InetAddress.getByAddress(quads);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			mBroadcastAddress = null;
		}
	}
}
